package com.halopay.controler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 本地上传文件
 * @author mingpingqiang on 2018/12/4/11:34
 * Created by mingpingqiang on 2018/12/4/11:34
 */
@RestController
@RequestMapping("/api/uploadFile")
public class UploadFileController {
    private static final Logger log = LoggerFactory.getLogger(UploadFileController.class);
    private static final  String path = "C:\\Users\\11458\\Desktop\\";
    @RequestMapping("/uploadOne")
    public Map<String,String> uploadOne(@RequestParam("file") MultipartFile file) throws IOException {
        log.info("[文件类型] ~ [{}]",file.getContentType());
        log.info("[文件名称] ~ [{}]",file.getOriginalFilename());
        log.info("[文件大小] ~ [{}]",file.getSize());
        file.transferTo(new File(path + file.getOriginalFilename()));
        Map<String,String> map = new HashMap<>();
        map.put("contentType",file.getContentType());
        map.put("fileName",file.getOriginalFilename());
        map.put("fileSize",file.getSize() + "");
        return map;
    }

    @RequestMapping("/uploadMany")
    public List<Map<String,String>> uploadMany(@RequestParam("file") MultipartFile[] files) throws IOException {
        if (files == null || files.length == 0){
            return null;
        }
        List<Map<String,String>> mapList = new ArrayList<>();
        for (MultipartFile file : files){
            log.info("[文件类型] ~ [{}]",file.getContentType());
            log.info("[文件名称] ~ [{}]",file.getOriginalFilename());
            log.info("[文件大小] ~ [{}]",file.getSize());
            file.transferTo(new File(path + file.getOriginalFilename()));
            Map<String,String> map = new HashMap<>();
            map.put("contentType",file.getContentType());
            map.put("fileName",file.getOriginalFilename());
            map.put("fileSize",file.getSize() + "");
            mapList.add(map);
        }
        return mapList;
    }

    @RequestMapping("/uploadBase64")
    public void uploadBase64(String base64) throws IOException {
        final File tempFile = new File(path + "test.jpg");
        String[] d = base64.split("base64,");
        final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]);
        FileCopyUtils.copy(bytes,tempFile);
    }

}
